package com.ll.wechat.chat.activity;

import java.util.ArrayList;
import java.util.Collection;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ll.wechat.R;
import com.ll.wechat.base.activity.BaseActivity;
import com.ll.wechat.base.app.Constant;
import com.ll.wechat.base.app.User;
import com.ll.wechat.base.net.NetCallBackListener;
import com.ll.wechat.base.net.NetUtil;
import com.ll.wechat.base.utils.thread.ThreadPoolUtil;
import com.ll.wechat.base.utils.widget.MyToast;
import com.ll.wechat.base.utils.widget.TextWatcherAdapter;
import com.ll.wechat.base.utils.widget.TextWatcherAdapter.TextWatcherListener;
import com.ll.wechat.chat.adapter.ChatViewListAdapter;
import com.ll.wechat.chat.widget.ChatEditext;
import com.ll.wechat.chat.widget.ChatEditext.FaceIconOnClickListener;
import com.ll.wechat.chatRecord.bean.ChatRecord;
import com.ll.wechat.database.DataBaseHelperUtil;

/**
 * 聊天界面
 * 
 * @ClassName: ChatActivity
 * @author yeliangliang
 * @date 2015-7-29 下午5:56:28
 */
public class ChatActivity extends BaseActivity implements TextWatcherListener, OnClickListener {
	private ArrayList<ChatRecord> chatMessageList;// 聊天信息集合
	private ListView chatListView;// 聊天信息列表
	private ChatViewListAdapter mAdapter;// 聊天信息列表适配器
	private ChatEditext edt_input;// 输入框
	private TextView tv_post;// 发送按钮
	private ImageView img_add;// 添加按钮
	private User user;
	private AbstractXMPPConnection connection;// 连接器
	private String name;// 昵称
	private String passName;// 用户名
	private Chat chat;
	private ChatManager chatManager;
	private MessageBroadCastReceiver mReceiver;// 消息接收广播
	private InputMethodManager imm; // 输入法管理器
	private DataBaseHelperUtil dataBaseHelperUtil;
	private final static int DATA_SUCCESS = 10000;
	private RelativeLayout faceRelativeLayout;// 表情选择框
	private boolean tag_face = false;// 表情选择框打开的tag

	@Override
	public void initView() {
		setContentView(R.layout.activity_chat);
		// 获取聊天记录
		getChatRecord();
		// 取消actionBar的图标
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		getActionBar().setTitle(name);
		// 声明控件以及添加监听
		findIdAndSetClick();
	}

	/**
	 * 获取聊天记录
	 * 
	 * @author yeliangliang
	 * @date 2015-8-6 下午6:11:03
	 * @version V1.0
	 * @return void
	 */
	private void getChatRecord() {
		passName = getIntent().getStringExtra("passName");
		name = getIntent().getStringExtra("name");
		dataBaseHelperUtil = DataBaseHelperUtil.getInstance(this);
		// 获取当前对象的聊天信息
		searchNowChatRecord();
	}

	/**
	 * 获取当前对象的聊天信息
	 * 
	 * @author yeliangliang
	 * @date 2015-8-7 上午11:27:17
	 * @version V1.0
	 * @return void
	 */
	private void searchNowChatRecord() {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				handler.obtainMessage(DATA_SUCCESS,
						dataBaseHelperUtil.searchNowChatRecord(passName)).sendToTarget();

			}
		};
		ThreadPoolUtil.insertTaskToCatchPool(runnable);
	}

	/**
	 * 声明控件以及添加监听
	 * 
	 * @author yeliangliang
	 * @date 2015-8-3 上午11:31:18
	 * @version V1.0
	 * @return void
	 */
	private void findIdAndSetClick() {
		faceRelativeLayout = (RelativeLayout) findViewById(R.id.rl_face);
		chatListView = (ListView) findViewById(R.id.listView_chat);
		edt_input = (ChatEditext) findViewById(R.id.edt_input);
		tv_post = (TextView) findViewById(R.id.tv_post);
		img_add = (ImageView) findViewById(R.id.img_add);
		// 添加状态改变监听
		edt_input.addTextChangedListener(new TextWatcherAdapter(edt_input, this));
		edt_input.setOnClickListener(this);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 设置输入框被点击的监听
		edt_input.setFaceIconOnClickListener(new FaceIconOnClickListener() {

			@Override
			public void clickFace(boolean isFace) {
				if (!isFace) {
					// 点击的不是表情图标
					imm.showSoftInput(edt_input, InputMethodManager.SHOW_FORCED);
					// 关闭表情选择框
					faceRelativeLayout.setVisibility(View.GONE);
					tag_face = false;
				} else {
					// 点击了表情图标
					imm.hideSoftInputFromWindow(edt_input.getWindowToken(), 0);// 关闭软键盘
					if (tag_face) {
						// 关闭表情选择
						faceRelativeLayout.setVisibility(View.GONE);
						tag_face = false;
					} else {
						// 打开表情选择框
						faceRelativeLayout.setVisibility(View.VISIBLE);
						tag_face = true;
					}

				}
				chatListView.setSelection(chatMessageList.size() - 1);
			}
		});
		tv_post.setOnClickListener(this);
	}

	@Override
	public void initData() {
		user = User.getInstance();
		connection = user.getConnection();
		chatMessageList = new ArrayList<ChatRecord>();
		mAdapter = new ChatViewListAdapter(ChatActivity.this, chatMessageList);
		chatListView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		// 建立聊天连接
		if (connection != null) {
			chatManager = User.getInstance().getChatManager();
			chat = chatManager.createChat(passName);
		}
	}

	/**
	 * 输入框动态监听
	 */
	@Override
	public void onTextChanged(EditText view, String text) {
		if (TextUtils.isEmpty(text.trim())) {
			// 显示添加按钮
			img_add.setVisibility(View.VISIBLE);
			tv_post.setVisibility(View.GONE);
		} else {
			// 显示发送按钮
			img_add.setVisibility(View.GONE);
			tv_post.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_post:// 发送按钮
			imm.hideSoftInputFromWindow(edt_input.getWindowToken(), 0);// 关闭软键盘
			if (!NetUtil.isNetConnection()) {
				MyToast.showToast(ChatActivity.this, "网络断开连接");
				return;
			}
			if (connection == null || chatManager == null) {
				// 与服务器连接已断开
				MyToast.showToast(ChatActivity.this, "服务器已断开");
				return;
			}
			postMessage(new ChatRecord("", passName.split("@")[0], passName,
					System.currentTimeMillis() + "", edt_input.getText().toString(), "", "my", "0"));
			edt_input.setText("");
			break;
		case R.id.edt_input:
			chatListView.setSelection(chatMessageList.size() - 1);
			break;
		default:
			break;
		}
	}

	/**
	 * 发送信息
	 * 
	 * @author yeliangliang
	 * @date 2015-8-3 上午11:32:53
	 * @version V1.0
	 * @return void
	 */
	private void postMessage(final ChatRecord chatMessage) {
		chatMessageList.add(chatMessage);
		mAdapter.notifyDataSetChanged();
		chatListView.setSelection(chatMessageList.size() - 1);
		NetUtil.postMessage(ChatActivity.this, chatMessage, chat, new NetCallBackListener() {

			@Override
			public void responseSuccess(int i, Object o) {
				saveChatRecord(passName, chatMessage.getContent(), "my");
			}

			@Override
			public void responseFailed(int i) {
				handler.obtainMessage(i).sendToTarget();
			}

			@Override
			public void responseError(int i) {

			}
		});
	}

	/**
	 * 接收消息
	 * 
	 * @param msg
	 * @author yeliangliang
	 * @date 2015-8-4 下午1:38:52
	 * @version V1.0
	 * @return void
	 */
	private void receiverMessage(ChatRecord msg) {
		if (chatListView.getLastVisiblePosition() == (chatMessageList.size() - 1)) {
			// 判断当前的滑动条是否在底部
			// 在底部
			chatMessageList.add(msg);
			mAdapter.notifyDataSetChanged();
			chatListView.setSelection(chatMessageList.size() - 1);
		} else {
			chatMessageList.add(msg);
			mAdapter.notifyDataSetChanged();
		}

	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.REQUEST_FAILD:
				MyToast.showToast(ChatActivity.this, "发送失败");
				break;
			case DATA_SUCCESS:// 信息查询成功
				if (chatMessageList == null) {
					chatMessageList = new ArrayList<ChatRecord>();
				}
				chatMessageList.clear();
				chatMessageList.addAll((Collection<? extends ChatRecord>) msg.obj);
				// 修改消息未读状态
				Runnable runnable = new Runnable() {

					@Override
					public void run() {
						dataBaseHelperUtil.modifyNewRecordStaues(chatMessageList.get(
								chatMessageList.size() - 1).getName());

					}
				};
				ThreadPoolUtil.insertTaskToCatchPool(runnable);
				mAdapter.notifyDataSetChanged();
				chatListView.setSelection(chatMessageList.size() - 1);
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onResume() {
		super.onResume();
		/**
		 * 注册消息接收广播
		 */
		if (mReceiver == null) {
			mReceiver = new MessageBroadCastReceiver();
		}
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.setPriority(1000);
		intentFilter.addAction(Constant.RECIVER_MESSAGE);
		registerReceiver(mReceiver, intentFilter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 注销广播
		if (mReceiver != null) {
			unregisterReceiver(mReceiver);
		}
	}

	/**
	 * 消息接收广播 接收来自服务器的消息提醒
	 * 
	 * @ClassName: MessageBroadCastReceiver
	 * @author yeliangliang
	 * @date 2015-8-4 上午11:57:37
	 */
	private class MessageBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String from = intent.getExtras().getString("from");
			String content = intent.getExtras().getString("body");
			// 判断是否为当前用户返回的消息
			if (from.equals(passName)) {
				// 0代表已阅
				mReceiver.setResultCode(0);
				saveChatRecord(from, content, "you");
				ChatRecord message = new ChatRecord("", passName.split("@")[0], passName,
						System.currentTimeMillis() + "", content, "", "you", "0");
				// 处理接收到的消息
				receiverMessage(message);
			} else {
				// 1代表未读
				mReceiver.setResultCode(1);
			}
		}

	}

	// 监听返回键，防止内存泄露
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if (tag_face) {
				tag_face = false;
				faceRelativeLayout.setVisibility(View.GONE);
				edt_input.displayIcon(false);
				return true;
			}
			finishActivity(ChatActivity.this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 存储聊天信息到本地数据库
	 * 
	 * @param chatRecord
	 * @author yeliangliang
	 * @date 2015-8-6 下午3:52:07
	 * @version V1.0
	 * @return void
	 */
	private void saveChatRecord(final String from, final String content, final String source) {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				ChatRecord chatRecord = new ChatRecord();
				chatRecord.setContent(content);
				chatRecord.setName(from.split("@")[0]);
				chatRecord.setPassName(from);
				chatRecord.setSource(source);
				chatRecord.setTime(System.currentTimeMillis() + "");
				chatRecord.setStaues("0");
				dataBaseHelperUtil.insertToTable(DataBaseHelperUtil.TABLE_NAME_CHAT_RECORD,
						chatRecord);
				dataBaseHelperUtil.insertNewRecord(chatRecord);
			}
		};
		ThreadPoolUtil.insertTaskToCatchPool(runnable);

	}

	/**
	 * 创建ActionBar菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.chat, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * ActionBar的点击监听
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finishActivity(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
